<?php
define('HASH_ALGO', 'md5');
//连接连接数据库的PHP文件
$dbi = include('conn.php');

if (!isset($_POST['submit'])){
    exit('非法访问');
}

$username = $_POST['username'];
$password = $_POST['password'];
$retype = $_POST['retype'];

//判断注册信息
if (!preg_match('/^[\w\x80-\xff]{3,60}$/', $username)){
    exit('用户名格式不符合规定 <a onclick="history.back(-1);">返回</a>');
}
if(strlen($password) < 6){
    exit('密码长度不符合规定 <a onclick="history.back(-1);">返回</a>');
}
if($password != $retype){
    exit('两次密码输入不符 <a onclick="history.back(-1);">返回</a>');
}
//写入注册数据
$stmt = $dbi->prepare("select count(`username`) as user_num from user where username=?");
$stmt->execute([$username]);
$userNum = $stmt->fetch()['user_num'];
if ($userNum > 0){
    exit(sprintf('用户名 %s 已经存在 <a onclick="history.back(-1);">返回</a>', $username));
}
//写入数据
$salt = uniqid();
$password = hash_hmac(HASH_ALGO, $password, $salt);
$passwordStr = sprintf('%s:%s:%s', HASH_ALGO, $salt, $password);
$sql = "INSERT INTO user (`username`, `password`) VALUES (?, ?)";
$stmt = $dbi->prepare($sql);
$result = $stmt->execute([$username, $passwordStr]);

if ($result){
    exit('你他娘的的注册成功了，赶紧他娘的去登录吧 <a href="login.php">跳转（临时）</a>');
} else {
    exit('注册失败了，我觉得有点不对头 <a onclick="history.back(-1);">返回</a>');
}
?>